package com.hz.cheetah.hub.protocol;

import com.hz.cheetah.common.net.NetUtil;

import java.io.IOException;
import java.net.*;
import java.util.HashMap;

/**
 * Created by yangchuan on 16/6/24.
 */
public class CheetahURL implements java.io.Serializable {

    private static int defaultWight = 100;

    private volatile java.net.URL url;

    private String urlString;

    private Object obj = new Object();

    private String address;

    private InetSocketAddress remoteAddress;

    private long serverId;

    /**
     * 权重
     */
    private int weight = defaultWight;

    static{
       // URL.setURLStreamHandlerFactory(new CheetahStreamHandlerFactory());
    }


    public CheetahURL(String urlStr){
        this.urlString = urlStr;
    }

    public static CheetahURL pase2CURL(String urlString){
        return new CheetahURL(urlString);
    }

    public void init(){
        pase2URL();
        String query = url.getQuery();
        HashMap<String,String> params = getMapByUrl(query);
        String w = params.get("weight");
        if(w != null){
            weight =Integer.valueOf(w);
        }
        address = url.getHost()+":"+url.getPort();
        remoteAddress = new InetSocketAddress(url.getHost(),url.getPort());
        serverId = NetUtil.stringIpPort2ServerUID(address);
    }

    /**
     * 将url 转发为普通URL
     * @return
     */
    public URL pase2URL(){
        if(url == null) {
            synchronized (obj) {
                if(url == null) {
                    try {
                        urlString = URLDecoder.decode(urlString,"UTF-8");
                        url = new URL(null,urlString,urlStreamHandler);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return url;
    }

    URLStreamHandler urlStreamHandler = new URLStreamHandler() {
        @Override
        protected URLConnection openConnection(URL u) throws IOException {
            return null;
        }
    };

    /**
     * 得到权重
     * @return
     */
    public int getWeight(){
        return weight;
    }

    private  HashMap<String,String> getMapByUrl(String data){
        HashMap<String,String> result = new HashMap<>();
        if(data == null || data.length() == 0){
            return result;
        }
        String name,value;
        int m,n;
        for(;;){

            m = data.indexOf("=");
            n = data.indexOf("&");

            if(m < 0 && n < 0){
                break;
            }

            // 例：a&ss= or  =&ss=sam
            if(m == -1 || m == n - 1){
                data = data.substring(n+1);
                continue;
            }

            //=号不能在第一个位置，也不能小于&链接符号的位置
            if(m > 0 && (m < n || n < 0)) {
                name = data.substring(0, m);
                if(n < 0){
                    value = data.substring(m + 1);
                    result.put(name,value);
                    break;
                }else {
                    value = data.substring(m + 1, n);
                    result.put(name,value);
                }
            }
            //当第一个位置是＝号是先去掉等号，否则去掉&链接符号之前的字符串。＝ss=tt&=ss=0
            n = m == 0 ? m : n;
            data = data.substring(n+1);
        }

        data = null;
        name = null;
        value = null;
        return result;
    }


    public String getHost(){
        return url.getHost();
    }

    public int getPort(){
        return url.getPort();
    }

    public String getAdress(){
        return address;
    }

    public InetSocketAddress getRemoteAddress(){
        return this.remoteAddress;
    }

    public long getServerId(){
        return serverId;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        CheetahURL that = (CheetahURL) o;

        return urlString.equals(that.urlString);

    }

    @Override
    public int hashCode() {
        return urlString.hashCode();
    }


}
